﻿/// <reference path = "Base.ts" />
namespace VantCellTypes {
    interface ISelectorCellTypeParam extends IInputBaseParam {
        useBinding: boolean;
        options: any;
        bindingOptions: any;
        SelectorConfig: ISelectorConfig;
        AllowAddEmptyItem: boolean;
        EmptyItemLabel: boolean;
    }
    interface ISelectorConfig {
        title: string;
        confirmButtonText: string;
        cancelButtonText: string;
        itemHeight: number;
        visibleItemCount: number;
        showToolbar: boolean;
        swipeDuration: number;
    }

    export class SelectorCellType extends InputBase<ISelectorCellTypeParam> {
        public setDataSource(dataSource, userAction = false) {
            if (userAction) {
                this.vue.cellValue = null;
                this.commitValue();
            }
            const cloneDataSource = [...dataSource];
            if (this.cellType.AllowAddEmptyItem) {

                const label = this.cellType.EmptyItemLabel ?? "";

                if (!label) {
                    this.vue.placeholder = null;
                }

                cloneDataSource.unshift({ value: "", label });
            }
            return this.vue.setOptions(cloneDataSource);
        }

        public getEmptyValue(options) {
            return options.find(o => o.value === "")?.label || null;
        }

        public onPageLoaded(info: Forguncy.Plugin.CellTypeInfo) {
            const self = this;
            const cellType = this.cellType;
            const config = cellType.SelectorConfig;
            const input = this.getInputTemplate(`@click="onClick" clear-trigger="always" @clear="onClear" :clear-icon="clearIconName" `);

            const optionStr = this.getCustomSlotByPath(SlotPath.pickerOption);

            let options = [];
            let value = null;
            if (!cellType.useBinding) {
                options = cellType.options.map(o => self.convertOption(o));
                value = this.getEmptyValue(options);
            }
            const option = {
                template: `
<div class="fgc-vant-inputContainer">
    ${input}
    <van-popup v-model:show="show" position="bottom" teleport="body">
      <van-picker
        ref="van-picker"
        :columns="columns"
        :title="title"
        :confirm-button-text="confirmButtonText"
        :cancel-button-text="cancelButtonText"
        :item-height="itemHeight"
        :visible-item-count="visibleItemCount"
        :show-toolbar="showToolbar"
        :swipe-duration="swipeDuration"
        @cancel="show=false"
        @confirm="onFinish"
        @change="onChange"
      >
        ${ optionStr ? "<template #option='data'>" + optionStr + "</template>" : "" }
      </van-picker>
    </van-popup>
</div>`,
                data() {
                    const baseData = self.getData(cellType);
                    let columns = [];
                    if (!cellType.useBinding && cellType.options && cellType.options.length > 0) {
                        columns = cellType.options.map(i => i.label);
                    }
                    const data = {
                        show: false,
                        columns: columns,
                        cellValue: "",
                        tempValue: null,
                        tempIndex: null,
                        ...getPickerValidToolbarOption(config),
                        options
                    };
                    config.showToolbar = !!config.showToolbar;
                    return { ...baseData, ...config, ...data, value };
                },
                computed: {
                    // 通过clear icon name 来控制clear icon的显示
                    clearIconName({ cellValue }) {
                        return cellValue === "" ? "" : undefined;
                    }
                },
                watch: {
                    value(newValue) {
                        if (self.isEmpty(newValue)) {
                            this.value = self.getEmptyValue(this.options);
                        }
                    },
                    show(value) {
                        if (!value && !this.showToolbar && this.tempIndex !== null) {
                            this.onFinish(this.tempValue, this.tempIndex);
                        }
                    }
                },
                methods: this.getDefaultMethods({
                    onFinish(value, index) {
                        this.show = false;
                        this.cellValue = self.isEmpty(index) ? "" : this.options[index].value;
                        this.value = value;
                        this.tempValue = null;
                        this.tempIndex = null;
                        self.commitValue();
                        self.validate();
                    },
                    onClear() {
                        this.onFinish(null, null);
                    },
                    onChange(value, index) {
                        this.tempValue = value;
                        this.tempIndex = index;
                    },
                    setOptions(dataSource) {
                        dataSource = dataSource.map(o => self.convertOption(o));
                        this.options = dataSource;
                        if (dataSource && dataSource.length) {
                            this.columns = dataSource.map(i => i.label);
                            this.updateValue();
                        }
                        else {
                            this.columns = [];
                            this.value = null;
                        }
                    },
                    onClick() {
                        if (!self.isReadOnly() && !self.isDisabled()) {
                            this.show = true;
                            if (this.options) {
                                /*eslint-disable-next-line*/
                                const index = this.options.findIndex(i => i.value == this.cellValue);
                                this.$nextTick(() => {
                                    this.$refs["van-picker"].setColumnIndex(0, index > 0 ? index : 0);
                                });
                            }
                        }
                    },
                    getValue() {
                        return this.cellValue;
                    },
                    setValue(value) {
                        if (this.cellValue !== value) {
                            this.cellValue = value?.toString() || "";
                            this.updateValue();
                        }
                    },
                    updateValue() {
                        /*eslint-disable-next-line*/
                        const item = this.options.filter(i => i.value == this.cellValue)[0];
                        this.value = item ? item.label : this.cellValue;
                    },
                }),
                mounted() {
                    self.setFontToInputDom(this);

                    $(".van-field__control", self.container).attr("readonly", "readonly");
                }
            };

            this.createVueApp(option);

            if (cellType.useBinding) {
                SupportDataSourceCellType.refreshData(this, cellType.bindingOptions, (dataSource, userAction) => {
                    this.setDataSource(dataSource, userAction);
                }, true, <Forguncy.Plugin.queryDataOption>{
                    distinct: true
                });
            }

            super.onPageLoaded(info);
        }

        private getSelectedItem() {
            return this.vue.options.find(option => option.value === this.vue.cellValue) || null;
        }

        public SetDataSourceByStringArray(dataSource: string[]) {
            if (!dataSource) {
                dataSource = [];
            }
            if (typeof dataSource === "string") {
                dataSource = JSON.parse(dataSource);
            }
            const objSource = dataSource.map(i => <any>{
                "value": i,
                "label": i,
            });
            this.setDataSource(objSource);
        }

        public SetDataSourceByObjArray(dataSource: any[], valueProperty: string, labelProperty: string) {
            if (!dataSource) {
                dataSource = [];
            }
            if (typeof dataSource === "string") {
                dataSource = JSON.parse(dataSource);
            }
            if (!labelProperty) {
                labelProperty = valueProperty;
            }
            const objSource = dataSource.map(i => <any>{
                "value": i[valueProperty],
                "label": i[labelProperty],
            });
            this.setDataSource(objSource);
        }

        public ShowPopup() {
            this.vue.onClick();
        }

        public GetSelectedText() {
            return {
                SelectedText: this.getSelectedItem()?.label
            };
        }
        private convertOption(item) {
            return {
                ...item,
                value: item.value ?? "",
                label: this.format(item.label)
            };
        }
    }
}

Forguncy.Plugin.CellTypeHelper.registerCellType("Vant.CellTypes.Selector, Vant", VantCellTypes.SelectorCellType);